<template>
  <div class="management">

    <el-card style="margin-bottom: 20px;border: none;" shadow="never">
      <div class="management__header">
        <el-row class="search-box">
          <el-col>
            <div class="management__header--right">
              <div class="management__header--title">合同名称</div>
              <el-input
                v-model="managementParams.name"
                placeholder="请输入合同名称"
                clearable
                @keyup.enter.native="handleSearch"
                @clear="handleSearch"
              />
              <div class="management__header--right" style="margin-left: 30px;">
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="danger" @click="resetSearchInfo">重置</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-card style="border: none;" shadow="never">
      <div class="management__header--left">
        <el-button
          type="primary"
          @click="handleOpenDialog('create')"
        >
          添加合同
        </el-button>
        <el-button
          type="danger"
          :disabled="removeIds.length <= 0"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>
      <div class="management__list">
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="list"
          border
          :row-key="getRowKey"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            align="center"
            reserve-selection
          />
          <el-table-column label="合同名称" prop="name" align="center" />
          <el-table-column label="创建时间" prop="created_at" align="center" />
          <el-table-column label="最后修改时间" prop="updated_at" align="center" />
          <el-table-column label="合同文件" align="center">
            <template slot-scope="scope">
              <a :href="scope.row.file">
                <el-button plain circle type="primary" icon="el-icon-download" />
              </a>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template v-slot="{ row }">

              <el-button
                circle
                plain
                type="primary"
                icon="el-icon-view"
                @click="handlePreview(row)"
              />

              <el-button
                circle
                plain
                type="primary"
                icon="el-icon-edit"
                @click="handleOpenDialog('edit', row)"
              />

              <el-button
                circle
                plain
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(row)"
              />

            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="management__page">
        <Pagination
          :total="total"
          :limit="managementParams.paginate"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <el-dialog
      :visible.sync="dialogOptions.show"
      :title="dialogOptions.title"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <WordRecognition
        ref="wordRecognitionRef"
        :type="type"
        @complete="handleComplete"
      />
    </el-dialog>
    <FilePreviewDialog
      :visible.sync="filePreviewDialog.visible"
      :title="filePreviewDialogTitle"
      :file-path="filePreviewDialog.filePath"
      width="800px"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import WordRecognition from './components/WordRecognition'
import FilePreviewDialog from '@/components/FilePreviewDialog/FilePreviewDialog.vue'
import '@vue-office/docx/lib/index.css'
import { agree, setUpAgree, modifyAgree, deleteAgree } from '@/api/agree'
export default {
  name: '',
  components: {
    Pagination,
    WordRecognition,
    FilePreviewDialog
  },
  data() {
    return {
      total: undefined,
      type: 'create',
      loading: false,
      managementParams: {
        paginate: 10,
        page: 1,
        name: ''
      },
      dialogOptions: {
        show: false,
        title: '添加合同'
      },
      formData: {
        name: '',
        file: '',
        value: null
      },
      list: [],
      removeIds: [],

      filePreviewDialog: {
        visible: false,
        title: '',
        filePath: ''
      }
    }
  },
  computed: {
    filePreviewDialogTitle() {
      return `合同查看—${this.filePreviewDialog.title}`
    }
  },
  created() {
    this.initData()
  },
  methods: {
    getRowKey(row) {
      return row.id
    },

    initData() {
      this.getManagementList()
    },

    async getManagementList() {
      this.loading = true
      try {
        const res = await agree(this.managementParams)
        this.list = res.data
        this.total = res.meta.total
      } catch (error) {
        this.$message.error(error.message || '合同列表获取失败')
      } finally {
        this.loading = false
      }
    },

    handleEdit(row) {
      console.log('row ------>', row)
      this.getManagementById(row.id)
    },

    async getManagementById(agree_id) {
      try {
        const res = await agree({ agree_id })
        this.$refs.wordRecognitionRef.handleEdit(res.data)
      } catch (error) {
        console.log('error ------>', error)
      }
    },

    handleDelete(row) {
      this.removeIds = []
      this.removeIds.push(row.id)
      const agree_id = JSON.stringify(this.removeIds)
      this.removeConfirmAtion(agree_id)
    },

    handleBatchDelete() {
      const agree_id = JSON.stringify(this.removeIds)
      this.removeConfirmAtion(agree_id)
    },

    removeConfirmAtion(agree_id) {
      this.$confirm(
        '是否删除所选中的合同',
        '提示',
        { cancelButtonText: '取消', confirmButtonText: '继续删除', type: 'warning' }
      ).then(() => {
        this.deleteAgreeApi({ agree_id })
      }).catch(() => {
        this.removeIds = []
        this.$message.info('取消删除')
      })
    },

    async deleteAgreeApi(params) {
      try {
        await deleteAgree(params)
        this.$message.success('删除成功')
        this.refresh()
        this.$refs.tableRef.clearSelection()
      } catch (error) {
        this.$message.error(error.message || '删除失败')
      }
    },

    handleSelectionChange(e) {
      this.removeIds = e.map(item => item.id)
    },

    handlePagination(e) {
      this.managementParams.page = e.page
      this.managementParams.paginate = e.limit
      this.getManagementList()
    },

    handleSearch() {
      this.managementParams.page = 1
      this.getManagementList()
    },

    resetSearchInfo() {
      this.managementParams = this.$options.data().managementParams
      this.managementParams.name = this.$options.data().managementParams.name
      this.getManagementList()
    },

    refresh() {
      this.getManagementList()
    },

    handleOpenDialog(type, row) {
      this.reset()
      this.type = type
      if (type === 'create') {
        this.dialogOptions.title = '添加合同'
      } else {
        this.dialogOptions.title = '编辑合同'
        this.handleEdit(row)
      }
      this.dialogOptions.show = true
    },

    reset() {
      this.formData = this.$options.data().formData
    },

    handleComplete(e) {
      this.formData.file = e.file
      this.formData.value = e.value
      this.formData.name = e.name
      if (!e.id) {
        this.createAgreeApi()
      } else {
        this.formData.agree_id = e.id
        this.editAgreeApi()
      }
    },

    async createAgreeApi() {
      try {
        const res = await setUpAgree(this.getParams())
        if (res.code === 200) {
          this.$message.success('创建成功')
          this.dialogOptions.show = false
          this.refresh()
        }
      } catch (error) {
        this.$message.error(error.message || '创建失败')
      }
    },

    async editAgreeApi() {
      try {
        const res = await modifyAgree(this.getParams())
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.dialogOptions.show = false
          this.refresh()
        }
      } catch (error) {
        this.$message.error(error.message || '修改失败')
      }
    },

    getParams() {
      return {
        ...this.formData,
        value: JSON.stringify(this.formData.value)
      }
    },

    handleDialogClose() {
      this.$refs.wordRecognitionRef.manualClear()
      this.type = 'create'
    },

    handlePreview(row) {
      this.filePreviewDialog.filePath = row.file
      this.filePreviewDialog.title = row.name
      this.filePreviewDialog.visible = true
    }

  }
}
</script>

<style scoped lang='scss'>
.management {
  padding: 20px;

  &__header {
    display: flex;

    &--left {
      margin-bottom: 20px;
    }
    &--right {
      display: flex;
      align-items: center;
    }
    &--title {
      color: #8e8e8e;
      margin-right: 10px;
      width: 35%;
    }

  }

  &__page {
    margin: 15px 0 0 0;
    .pagination-container {
      padding: 0;
      margin: 0;
    }
  }
}
</style>
